package io.renren.modules.doc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.doc.dao.DocumentCategoryDao;
import io.renren.modules.doc.entity.DocumentCategoryEntity;
import io.renren.modules.doc.service.DocumentCategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("documentCategoryService")
public class DocumentCategoryServiceImpl extends ServiceImpl<DocumentCategoryDao, DocumentCategoryEntity> implements DocumentCategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String)params.get("name");

        QueryWrapper<DocumentCategoryEntity> queryWrapper = new QueryWrapper<DocumentCategoryEntity>();
        if(StringUtils.isNotBlank(name)){
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByAsc("order_num");

        IPage<DocumentCategoryEntity> page = this.page(
                new Query<DocumentCategoryEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<DocumentCategoryEntity> getCategoryTree() {
        // 获取所有分类
        List<DocumentCategoryEntity> allCategories = this.list(new QueryWrapper<DocumentCategoryEntity>()
            .orderByAsc("order_num"));
            
        // 构建树形结构
        List<DocumentCategoryEntity> rootCategories = allCategories.stream()
            .filter(category -> category.getParentId() == 0)
            .collect(Collectors.toList());
            
        rootCategories.forEach(root -> buildCategoryTree(root, allCategories));
        
        return rootCategories;
    }

    @Override
    public List<DocumentCategoryEntity> getChildren(Long parentId) {
        if(parentId == null){
            return new ArrayList<>();
        }
        
        QueryWrapper<DocumentCategoryEntity> queryWrapper = new QueryWrapper<DocumentCategoryEntity>()
            .eq("parent_id", parentId)
            .orderByAsc("order_num");
            
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCategory(DocumentCategoryEntity category) {
        // 如果没有设置排序号，则设置默认值
        if(category.getOrderNum() == null){
            category.setOrderNum(0);
        }
        this.save(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCategory(DocumentCategoryEntity category) {
        this.updateById(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategory(Long[] ids) {
        // 检查是否存在子分类
        List<DocumentCategoryEntity> children = this.list(new QueryWrapper<DocumentCategoryEntity>()
            .in("parent_id", Arrays.asList(ids)));
            
        if(children != null && !children.isEmpty()){
            throw new RuntimeException("存在子分类，无法删除");
        }
        
        this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 递归构建分类树
     */
    private void buildCategoryTree(DocumentCategoryEntity parent, List<DocumentCategoryEntity> allCategories) {
        List<DocumentCategoryEntity> children = allCategories.stream()
            .filter(category -> parent.getCategoryId().equals(category.getParentId()))
            .collect(Collectors.toList());
            
        if(!children.isEmpty()){
            parent.setChildren(children);
            children.forEach(child -> buildCategoryTree(child, allCategories));
        }
    }
}
